﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Business;
using AMM.Business.Project;
using AMM.Business.Store;
using AMM.CustomClassLibrary;
using AMM.CustomWinComponents.Validator;
using AMM.Model;
using AMM.Model.Business;
using AMM.Model.Project;

namespace AMM.UserControls {
    public partial class OutStoreOrderEditControl : BaseEditControl {

        private FlexBindingSource<OutStoreOrder> _fbs;
        private ProduceConductProcessor _produceConductOrderProcessor;
        private QualityOrderProcessor _qualityOrderProcessor;
        private MaterialStoreProcessor _materialStoreProcessor;

        public override object BaseEditModel {
            get {
                this._fbs.CurrentItem.OutStoreOrderDetails =
                    this.dgvMaterialEdit.GetDataSourceEx<OutStoreOrderDetail>(this._fbs.CurrentItem.ClassStatus != ClassStatus.Added);
                return this._fbs.CurrentItem;
            }
            set {
                if (this._fbs == null) { this._fbs = new FlexBindingSource<OutStoreOrder>(); }
                this._fbs.CurrentItem = (OutStoreOrder)value;
            }
        }

        public OutStoreOrderEditControl() {
            this.InitializeComponent();
        }

        private void BindMaterial(int produceConductId) {
            MaterialProcessor materialProcessor = new MaterialProcessor(int.MaxValue);
            List<MaterialViewModel> materialList = materialProcessor.FetchMaterialViewModelListByProduceConductId(produceConductId);
            if (materialList.Count == 0) {
                materialList = materialProcessor.FetchMaterialViewModelList(new MaterialSearchModel() { IsEnabled = true });
            }
           
            //if (produceConductId == 0) {
            //    MaterialSearchModel searchModel = new MaterialSearchModel() { IsEnabled = true };
            //    materialList = materialProcessor.FetchMaterialViewModelList(searchModel);
            //}
            //else {
            //    materialList = materialProcessor.FetchMaterialViewModelListByProcumentOrderId(produceConductId);
            //}

            this.Material.DisplayMemberEx = "Code";
            this.Material.ValueMemberEx = "Key";
            this.Material.HeightEx = 300;
            this.Material.WidthEx = 400;
            this.Material.PageSizeEx = 20;
            this.Material.DataBind(new MaterialViewModel(), x => new { x.MaterialType, x.Code, x.Name, x.Remarks }, materialList);
        }

        private void BindProduceConduct() {
            ProduceConductSearchModel searchModel = new ProduceConductSearchModel();
            ProduceConductProcessor produceConductProcessor = new ProduceConductProcessor();
            List<ProduceConductViewModel> produceConductList = produceConductProcessor.FetchProduceConductViewModelList(searchModel);
            /*
            if (produceConductOrderId != 0 && !produceConductList.Any(x => x.Key == produceConductOrderId)) {
                ProduceConduct produceConductOrder = produceConductProcessor.FetchProduceConductById(produceConductOrderId);
                produceConductList.Add(new ProduceConductViewModel() {
                    Key = produceConductOrder.ProduceConductId,
                    Code = produceConductOrder.Code
                });
            }
            */

            this.ddlProduceConduct.DisplayMemberEx = "ProduceConductCode";
            this.ddlProduceConduct.ValueMemberEx = "Key";
            this.ddlProduceConduct.HeightEx = 300;
            this.ddlProduceConduct.WidthEx = 400;
            this.ddlProduceConduct.PageSizeEx = 20;
            this.ddlProduceConduct.DataBind(new ProduceConductViewModel(), x => new {
                x.ProduceConductCode,
                x.CustomerOrderCode,
                x.ProcurementOrderCode
            }, produceConductList);
        }

        private void CreateFormBindings() {
            this._fbs.CreateBinding(this.ddlProduceConduct, x => x.SelectedValueEx, y => y.ProduceConductId);
            this._fbs.CreateBinding(this.cmbOutStoreType, x => x.SelectedValue, y => y.OutStoreTypeId);
            this._fbs.CreateBinding(this.cmbProductUnit, x => x.SelectedValue, y => y.ProductUnitId);
            this._fbs.CreateBinding(this.tbRemarks, x => x.Text, y => y.Remarks);
            this._fbs.CreateBinding(this.tbCode, x => x.Text, y => y.Code);
        }

        private void BindValidation() {
            this.ValidatorForEdit.SetType(this.tbCode, ValidationType.Required | ValidationType.RegularExpression);
            this.ValidatorForEdit.SetRequiredMessage(this.tbCode, this.RequiredMessage);
            this.ValidatorForEdit.SetRegularExpression(this.tbCode, "^[A-Za-z0-9-]+$");
            this.ValidatorForEdit.SetRegularExpressionMessage(this.tbCode, "编码只能由字母，数字，连接线组成");

            this.ValidatorForEdit.SetType(this.ddlProduceConduct, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.ddlProduceConduct, this.RequiredMessage);

            this.ValidatorForEdit.SetType(this.cmbOutStoreType, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.cmbOutStoreType, this.RequiredMessage);
        }

        private void BindDataGridView() {
            this.dgvMaterialEdit.DataSourceEx = this._fbs.CurrentItem.OutStoreOrderDetails.ToList();
        }

        private void OutStoreEditControl_Load(object sender, EventArgs e) {
            if (this._fbs == null) { this._fbs = new FlexBindingSource<OutStoreOrder>(); }
            this._produceConductOrderProcessor = new ProduceConductProcessor();
            this._qualityOrderProcessor = new QualityOrderProcessor();
            this._materialStoreProcessor = new MaterialStoreProcessor();

            this.BindMaterial(this._fbs.CurrentItem.ProduceConductId);
            this.BindBasics(this.cmbOutStoreType, BasicsType.MaterialOutStoreType);
            this.BindBasics(this.cmbProductUnit, BasicsType.ProduceUnit);
            this.BindProduceConduct();
            this.BindDataGridView();
            this.CreateFormBindings();
            this.BindValidation();

            this.ddlProduceConduct.Enabled = false;
            if (this._fbs.CurrentItem.ClassStatus == ClassStatus.Added) {
                string autoCode = CommonHelper.GenerateAutoCode("MO");
                int maxNumber = new OutStoreOrderProcessor().GetTheMaxFlowNumber(autoCode);
                this.tbCode.Text = this._fbs.CurrentItem.Code = CommonHelper.GendrateSpecificCode(autoCode, maxNumber);
                this.ddlProduceConduct.Enabled = true;
            }
        }

        private void ddlSuspense_ValueChanged(object sender, EventArgs e) {
            if (this.ddlProduceConduct.SelectedValueEx == null) { return; }
            if (this._fbs.CurrentItem.ClassStatus == ClassStatus.Updated) { return; }
            int produceConductId = Convert.ToInt32(this.ddlProduceConduct.SelectedValueEx);
            this.BindMaterial(produceConductId);

            this._fbs.CurrentItem.OutStoreOrderDetails.Clear();
            try {
                this._fbs.CurrentItem.OutStoreOrderDetails =
                    this._produceConductOrderProcessor.FetchProduceConductMaterialList(produceConductId);
            }
            catch { }
            this.BindDataGridView();
        }

        private void dgvMaterialEdit_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
            if (this.dgvMaterialEdit.Columns[e.ColumnIndex].Name == "Quantity") {
                decimal storeValue = Convert.ToDecimal(this.dgvMaterialEdit.Rows[e.RowIndex].Cells["StoreQuantity"].Value);
                decimal value = Convert.ToDecimal(this.dgvMaterialEdit[e.ColumnIndex, e.RowIndex].Value);
                this.dgvMaterialEdit.Rows[e.RowIndex].Cells["ErrMessage"].Value = storeValue < value ? "库存不足" : string.Empty;
            }
            if (this.dgvMaterialEdit.Columns[e.ColumnIndex].Name == "Material") {
                int materialId = Convert.ToInt32(this.dgvMaterialEdit.Rows[e.RowIndex].Cells["Material"].Value);
                List<MaterialStore> msList=this._materialStoreProcessor.FetchMaterialStoreByMaterialId(materialId);
                this.dgvMaterialEdit.Rows[e.RowIndex].Cells["StoreQuantity"].Value = msList.Count > 0 ? msList[0].Quantity : 0;
            }
        }
    }
}
